package com.sneakxy.cloudbase.platform.filters;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sneakxy.cloudbase.platform.utils.web.Response;
/**
 * 
 * @author 潜行的虚影
 *
 */
public class CloudBasePermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

	public static final String ERROR_UNAUTHORIZED = "用户未认证";
	
	public static final String ERROR_FORBIDDEN = "禁止访问功能";
	
	private ObjectMapper mapper = new ObjectMapper();
	
	private String encoding = "UTF-8";
	
	@Override
	protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
		HttpServletResponse resp = WebUtils.toHttp(response);
		responseSetting(resp);
        String json = mapper.writeValueAsString(Response.fail(HttpServletResponse.SC_UNAUTHORIZED, ERROR_UNAUTHORIZED));
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try(OutputStream os = resp.getOutputStream()) {
        	IOUtils.write(json, os, response.getCharacterEncoding());
        }
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		Subject subject = getSubject(request, response);
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
        	HttpServletResponse resp = WebUtils.toHttp(response);
        	responseSetting(resp);
        	String json = mapper.writeValueAsString(Response.fail(HttpServletResponse.SC_FORBIDDEN, ERROR_FORBIDDEN));
        	resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            try(OutputStream os = resp.getOutputStream()) {
            	IOUtils.write(json, os, response.getCharacterEncoding());
            }
        }
        return false;
	}
	
	protected void responseSetting(HttpServletResponse response) {
		response.setCharacterEncoding(getEncoding());
		response.setHeader("pragma", "no-cache") ;
		response.setHeader("cache-control", "no-cache") ;
		response.setHeader("Expires", "0") ;
		response.setContentType(StringUtils.join("application/json;charset=", response.getCharacterEncoding()));
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

}
